<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图书管理案例</title>
    <style>
        .tab {
            margin: auto;
            width: 530px;
            text-align: center;
        }

        .tab table {
            border-top: 1px solid #C2D89A;
            width: 100%;
            border-collapse: collapse;
        }

        .tab th,
        td {
            padding: 10;
            border: 1px dashed #F3DCAB;
            height: 35px;
            line-height: 35px;
        }

        .tab th {
            background-color: #F3DCAB;
        }

        .tab .book {
            padding-bottom: 10px;
            padding-top: 5px;
            background-color: #F3DCAB;
        }

        .tab .total {
            height: 35px;
            line-height: 35px;
            border-top: 1px solid #C2D89A;
            background-color: #F3DCAB;
        }
    </style>
</head>

<body>
    <div class="app">
        <div class="tab">
            <div>
                <h1>图书管理</h1>
                <div class="book">
                    <div>
                        <label for="id">编号:</label>
                        <input type="text" id="id" :disabled="true" v-model="id" v-focus>
                        <label for="name">名称:</label>
                        <input type="text" id="name" v-model="name">
                        <button @click="addbook" :disabled="submitFlag">提交</button>
                    </div>
                </div>
                <div class="total">
                    <span>图书总数:</span>
                    <span>{{ total }}</span>
                </div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>编号</th>
                        <th>名称</th>
                        <th>时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item,index) in books" :key="item.id">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.date | format('yyyy-MM-dd hh:mm:ss')}}</td>
                        <td>
                            <a href="" @click.prevent="toEdit(item.id)">编辑</a>
                            <span>|</span>
                            <a href="" @click.prevent="delbook(item.id)">删除</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script src="./js/vue.js"></script>
    <script src="./js/axios.js"></script>
    <script>
        // 定义基准路径
        axios.defaults.baseURL = ' http://localhost:3000/'
        axios.interceptors.response.use(function (res) {
            return res.data;
        }, function (error) {
            console.log(error)
        })
        //自定义指令
        Vue.directive('focus', {
            // 钩子函数本身给提供的方法 能够让程序在某一个阶段做某件事
            //inserted 钩子函数h指的是在使用了自定义指令的元素中在父级加载好后执行
            inserted: function (el) {
                //el表示指令所绑定的元素
                el.focus();
            }
        })
        //过滤器
        Vue.filter('format', function (value, arg) {
            function dateFormat(date, format) {
                if (typeof date === "string") {
                    var mts = date.match(/(\/Date\((\d+)\)\/)/);
                    if (mts && mts.length >= 3) {
                        date = parseInt(mts[2]);
                    }
                }
                date = new Date(date);
                if (!date || date.toUTCString() == "Invalid Date") {
                    return "";
                }
                var map = {
                    "M": date.getMonth() + 1, //月份 
                    "d": date.getDate(), //日 
                    "h": date.getHours(), //小时 
                    "m": date.getMinutes(), //分 
                    "s": date.getSeconds(), //秒 
                    "q": Math.floor((date.getMonth() + 3) / 3), //季度 
                    "S": date.getMilliseconds() //毫秒 
                };

                format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
                    var v = map[t];
                    if (v !== undefined) {
                        if (all.length > 1) {
                            v = '0' + v;
                            v = v.substr(v.length - 2);
                        }
                        return v;
                    } else if (t === 'y') {
                        return (date.getFullYear() + '').substr(4 - all.length);
                    }
                    return all;
                });
                return format;
            }
            return dateFormat(value, arg);
        })
        //-------------------------
        // 1. 需求用v-mode为input输入框绑定双向数据
        // 2. 用v-for将data中的数据渲染到页面中
        // 3. 为编辑和删除按钮绑定一个点击事件，并且阻止默认行为
        // 4. 提交按钮中绑定一个添加事件 给列表添加图书
        // 5. 编辑图书事件
        //①为图书id设置一个状态 当
        var xm = new Vue({
            el: '.app',
            data: {
                id: '',
                name: '',
                isFlag: false,
                submitFlag: false,
                books: []

            },
            methods: {
                // 添加图书
                async addbook() {
                    if (this.isFlag) {
                        // 编辑图书
                        var ret = await axios.put('books/' + this.id, {
                            name: this.name
                        })
                        if (ret.status == 200) {
                            this.queryData()
                        }
                        this.isFlag = false
                    } else {
                        // 添加图书
                        var ret = await axios.post('books', {
                            name: this.name
                        })
                        if (ret.status === 200) {
                            this.queryData()
                        }
                    }
                    this.id = this.name = ''

                },
                async toEdit(id) {
                    // flag 用于区分编辑和添加操作
                    this.isFlag = true
                    // 编辑图书 点击编辑按钮
                    var ret = await axios.get('books/' + id)
                    this.id = ret.id
                    this.name = ret.name
                },
                async delbook(id) {
                    var ret = await axios.delete('books/' + id)
                    if (ret.status == 200) {
                        this.queryData()
                    }
                },
                queryData: async function () {
                    this.books = await axios.get('books')
                }
            },
            created: function () {

                this.queryData()

            },
            computed: {
                total: function () {
                    return this.books.length
                }
            },
            watch: {
                name: async function (val) {
                    var ret = await axios.get('books/book/' + this.name);
                    console.log(ret)
                    if (ret.status == 1) {
                        this.submitFlag = true
                    } else {
                        this.submitFlag = false
                    }
                }
            }

        })
    </script>
</body>

</html>